<?php

namespace app\merchant\controller;

use app\common\model\OrderModel;
use app\common\model\SettlementBillModel;
use app\common\model\WithdrawalCashModel;
use app\common\controller\Tools;
use think\Db;

class Order extends Common
{
    /*
     * 首页订单列表
     *@order_id修改的订单编号  order_shipping_status 订单当前物流状态1:全部订单 2：待发货 3：已发货
    */
    public function index ()
    {
        if(!input('?get.type') || input('get.type') == null){
            $order_shipping_status = 1;
        }else{
            $order_shipping_status = input('get.type');
        }
        switch($order_shipping_status){
            case 1:
                $where['gop.order_status']    = ['eq', 2];
                //$where['order.order_shipping_status'] = ['in', '1,2,3,4,5,6'];
                break;
            case 2: 
                $where['order.order_refund_goods_status'] = ['eq', 0];
                $where['gop.order_status']    = ['eq', 2];
                $where['order.order_shipping_status'] = ['eq', 1];
                break;
                //待结算
            case 3:
                $where['gop.order_status']    = ['eq', 2];
                $where['order.order_refund_goods_status'] = ['eq', 0];
                $where['order.order_shipping_status'] = ['in', [5,4]];
                break;
                //退款退货中
            case 4:
                $where['gop.order_status']    = ['eq', 2];
                $where['order.order_shipping_status'] = ['in', [2,3,4,5]];
                $where['order.order_refund_goods_status'] = ['eq', 2];
                break;
            case 5:
                $where['gop.order_status']    = ['eq', 2];
                $where['order.order_shipping_status'] = ['in', [6,7]];
                break;
            case 6:  //待归还
                $where['gop.order_status']    = ['eq', 2];
                $where['order.order_refund_goods_status'] = ['eq', 0];
                $where['order.order_shipping_status'] = ['in', [2,3]];
                break;
            case 7: // 续租订单
                $where['gop.order_status']    = ['eq', 2];
                $where['order.order_shipping_status'] = ['eq', 9];
                $where['order.relet_status'] = ['eq', 1];
                break;
        }
        $where['order.order_merchant_id'] = ['eq', session('merchant.merchant_id')];//['eq', session('merchant.merchant_id')];//,
        $where['order.order_is_delete'] = ['eq', 0];//session('merchant.merchant_id'),
        $page_number = 10;
        //获取快递模板的列表
        $data['merchant_list'] = Db::table('merchant')->where('merchant_id', 'eq', session('merchant.merchant_id'))->find();

        $data['order_list'] = OrderModel::order_sel($where, $page_number);
        foreach ($data['order_list'] as $k => $v){
            $data['order_list'][$k]['order_goods_rent_time'] =date("Y-m-d",$v['order_goods_rent_time']);
            $data['order_list'][$k]['order_goods_return_time'] =date("Y-m-d",$v['order_goods_return_time']) ;
            $data['order_list'][$k]['rent_price']= $data['order_list'][$k]['order_total_price']-$data['order_list'][$k]['order_deposit']-$data['order_list'][$k]['order_freight'];
            $relet_rent_pirce = Db::table("goods_order")
                ->where("relet_origin_id = {$v['order_id']} and order_is_delete = 0 and relet_status in (1,2,5)")->value("sum(order_total_price)");
            $data['order_list'][$k]['relet_rent_pirce'] = $relet_rent_pirce;
            $data['order_list'][$k]['is_relet'] = empty($relet_rent_pirce) ? 0 : 1;
        }
        $data['page'] = $data['order_list']->render();
        $data['page_list'] = $data['order_list']->total();
        $data['page_number'] = count($data['order_list']);
        $data['type'] = input('get.type');
        $data['year']=date('Y');
        $data['month']=date('m');
        return view('index', ['data' => $data]);
    }

    /*
     * 提现页面
    */
    public function cash(){
        $data = Db::table('merchant')->where('merchant_id', 'eq', session('merchant.merchant_id'))->find();
        return view('cash',['data' => $data]);
    }

    /*提现业务逻辑处理
       *@merchant_id  商户编号
    */
    public function withdrawals(){
        $user = Db::table('merchant')->where('merchant_id', 'eq', session('merchant.merchant_id'))->find();
        if(!$user){
            return returnJson('300', '用户不存在', '');
        }

        $count_money = Db::table('withdrawal_cash')->whereTime('withdrawal_cash_time', 'today')->sum('withdrawal_cash_money');
        if(floatval($count_money) >= 50000 ){
            return returnJson('300', '今日提现金额超出限制额度，你还可提取0元', '');
        }
        $withdrawal_cash_money = floatval(input('post.withdrawal_cash_money'));
        if($withdrawal_cash_money > 50000 - floatval($count_money)){
            return returnJson('300', '今日提现金额超出限制额度,你还可提取'.(50000 - floatval($count_money)).'元', '');
        }
        if($withdrawal_cash_money > 50000){
            $withdrawal_cash_money   = floatval(50000);
        }elseif($withdrawal_cash_money <= 0){
            return returnJson('300', '至少取1元', '');
        }

        if(floatval($user['merchant_coin']) < $withdrawal_cash_money){
            return returnJson('300', '账户余额不足', '');
        }else{
            $withdrawal_cash_balance = $user['merchant_coin']-$withdrawal_cash_money; //账户余额
        }
        $ret_add = Db::table('withdrawal_cash')->insert([
            'withdrawal_cash_merchant_id' => session('merchant.merchant_id'),
            'withdrawal_cash_time'        => time(),
            'withdrawal_cash_money'       => $withdrawal_cash_money,
            'withdrawal_cash_balance'     => $withdrawal_cash_balance,
            'withdrawal_cash_status'      => '1',
        ]);
        if(!$ret_add){
            return returnJson('300', '提现失败！请跟客服联系', '');
        }
        Db::table('merchant')->where('merchant_id', session('merchant.merchant_id'))->update(['merchant_coin' => $withdrawal_cash_balance]);
        return returnJson('200', '提现成功', '');
    }
    /*商户提现记录列表
       *@merchant_id  商户编号
    */
    public function recond(){
        $ret = Db::table('merchant')->where('merchant_id', 'eq', session('merchant.merchant_id'))->find();
        if(!$ret){
            return returnJson('300', '用户不存在', '');
        }
        $where['merchant_id'] = session('merchant.merchant_id');
        $page_number = "20";
        $data['withdrawal_cash'] = WithdrawalCashModel::withdrawal_cash_sel($where, $page_number);

        return view('recond',['data' => $data]);
    }

    /*发货订单填写页面
      *@order_id  订单编号  lease_day  租赁周期（天数）
    */
    public function confirm(){
        $where = ['order.order_id' => input('get.order_id')];
        $data['order_list'] = OrderModel::order_get($where);
        $data['lease_day'] = ($data['order_list']['order_goods_return_time']-$data['order_list']['order_goods_rent_time'])/86400;
        $order_id=input('get.order_id');
          $this->assign([
            'data' => $data,
            'order_id' => $order_id,
         ]);
        return view('confirm');
    }

    /*添加发货地址
     *@order_id  订单编号  data  发货物流信息   order_deliver_logistics_name发货物流公司  order_deliver_expressid 发货运单号
    */
    public function confirm_add(){
        //$as = vendor('Aliyun.Core.Profile.DefaultProfile');
        $order_id = input('param.order_id');
        $merchant_id = session('merchant.merchant_id');
		$datas= input('post.');
        $data = [
            'order_shipping_status'=> '2',
        ];
        $orderdata=Db::table('goods_order')
		->alias('a')
		->join('goods b','a.order_goods_id=b.goods_id','left')
        ->where('order_id','eq',$order_id)->find();
		OrderModel::order_shipping_edit($order_id, $data);	

        Db::table('goods_order_deliver')->where('order_id', 'eq', $order_id)->update([
            'order_deliver_expressid'=> isset($datas['order_deliver_expressid'])?$datas['order_deliver_expressid']:'',
            'order_logistics_name'=> isset($datas['order_deliver_logistics_name'])?$datas['order_deliver_logistics_name']:'',
			'order_deliver_company'=> isset($datas['order_deliver_company'])?$datas['order_deliver_company']:'',
        ]);
		
		Db::table('goods_order_time')->where('order_id', 'eq', $order_id)->update([
            'order_shipping_time' => time(),
        ]);

        //是快递才会发送短信和消息
        $order_deliver = Db::table('goods_order_deliver')->where('order_id','eq',$order_id)->find();
		if($order_deliver['order_express_type']==1)
        {
		//保存消息
	    Db::table('message_order')->insert([
            'merchant_id' => $merchant_id,
            'create_time'=> time(),
            'type'=> 2,
			'order_id'=>$order_id,
			'user_id'=>$orderdata['order_user_id'],
			'title'=>'订单消息',
			'content'=>'您购买的'.$orderdata['goods_name'].'已发货，收到货后请及时确认哦',
         ]);
	    //发送消息
        $user_tel=Db::table('user')
		->alias('a')
		->where('user_id','eq',$orderdata['order_user_id'])->find();
        $order_deliver_expressid=  $datas['order_deliver_expressid'];
        $order_deliver_logistics_name= $datas['order_deliver_company'];
        $order_sn= '***'.substr($orderdata['order_order_sn'], -6);
        $usertel=$user_tel['user_phone'];
        $ParamString = "{'ordersn':'$order_sn','logistics':'$order_deliver_logistics_name','expressid':'$order_deliver_expressid'}";
        $TemplateCode='SMS_90180063';//'SMS_89115027';
        //$this->OrderSendMessage($ParamString,$usertel,'租介',$TemplateCode);
        $tool=new Tools();
        $tool->sendMessage($ParamString, $usertel, '租介', $TemplateCode);
	    }
        return returnJson('1', '发货成功!');
    }

    /*
     * 生成订单结算单页面
     * @order_id订单编号
    */
    public function jiesuan(){
        $where = ['order.order_id' => input('get.order_id')];

        $data['order_list'] = Db::table('goods_order')->alias('order')
            ->field('order.order_id,order.order_goods_id,order.order_merchant_id,order.order_user_id,order.coupon_no,order.store_coupon_no,order.order_activity_id,order.order_activity_rent')
            ->field('order_rent_money,goods_amount,order_time_number,order_total_price,pay_price,actual_price')
            ->field('order_deposit,order_freight,order_refund_goods_status,order_relief_limit,gor.*')
            ->join('goods_order_pay gop','order.order_id = gop.order_id')
            ->join('goods g', 'order.order_goods_id = g.goods_id')
            ->join('goods_order_time got', 'order.order_id = got.order_id')
            ->join('goods_order_rent gor', 'order.order_id = gor.order_id')
            ->where($where)
            ->find();
        $data['order_list']['relet_price'] = 0;
        $data['order_list']['coupon_amount'] =0;
        $data['order_list']['store_coupon_amount'] =0;
        $data['order_list']['relet_price'] = 0;
        $data['order_list']['relet_rent_price'] = 0;
        /*处理红包减免*/
        $coupon_info = Db::table("zj_coupon_use")->alias("zcu")
            ->join('zj_coupon zc','zc.id=zcu.coupon_id','left')
            ->field("zc.use_range,zcu.used_amount")
            ->where("zcu.coupon_no in ('{$data['order_list']['coupon_no']}','{$data['order_list']['store_coupon_no']}')")
            ->select();
        if(!empty($coupon_info)){
            if(count($coupon_info) == 1){
                $data['order_list']['coupon_amount'] = $coupon_info[0]['use_range'] == 1 ? $coupon_info[0]['used_amount'] : 0;
                $data['order_list']['store_coupon_amount'] = $coupon_info[0]['use_range'] == 2 ? $coupon_info[0]['used_amount'] : 0;
            }else{
                foreach($coupon_info as $k => $v){
                    if($v['use_range'] == 1){
                        $data['order_list']['coupon_amount'] =$v['used_amount'];
                    }else{
                        $data['order_list']['store_coupon_amount'] =$v['used_amount'];
                    }
                }
            }
        }
        //续租订单信息
        $relet_where = [
            'order.relet_origin_id' => input('get.order_id'),
            'order.relet_status' => 2,
            'order.order_is_delete' => 0,
            'gop.order_status' => 2,
        ];
        $relet_order = Db::table('goods_order')->alias('order')
            ->field('order.order_id,order.coupon_no,order.store_coupon_no,order.actual_price,order.order_total_price')
            ->join('goods_order_pay gop','order.order_id = gop.order_id')
            ->where($relet_where)
            ->select();

        $relet_coupon_amount = $relet_store_coupon_amount = 0;
        if(!empty($relet_order)){
            foreach($relet_order as $k => $v){
                //续租订单实际付款金额
                $data['order_list']['relet_price'] = $data['order_list']['relet_price'] + $v['actual_price'];
                //处理续租订单红包信息
                $relet_coupon_info = Db::table("zj_coupon_use")->alias("zcu")
                    ->join('zj_coupon zc','zc.id=zcu.coupon_id','left')
                    ->field("zc.use_range,zcu.used_amount")
                    ->where("zcu.coupon_no in ('{$v['coupon_no']}','{$v['store_coupon_no']}')")
                    ->select();
                if(!empty($relet_coupon_info)){
                    if(count($relet_coupon_info) == 1){
                        $relet_coupon_amount = $relet_coupon_info[0]['use_range'] == 1 ? $relet_coupon_info[0]['used_amount'] : 0;
                        $relet_store_coupon_amount = $relet_coupon_info[0]['use_range'] == 2 ? $relet_coupon_info[0]['used_amount'] : 0;
                    }else{
                        foreach($relet_coupon_info as $k => $v){
                            if($v['use_range'] == 1){
                                $relet_coupon_amount =$v['used_amount'];
                            }else{
                                $relet_store_coupon_amount =$v['used_amount'];
                            }
                        }
                    }
                }
                //续租租金金额
                $data['order_list']['relet_rent_price'] = $data['order_list']['relet_rent_price']+$v['order_total_price'];
                $data['order_list']['coupon_amount'] += $relet_coupon_amount;
                $data['order_list']['store_coupon_amount'] += $relet_store_coupon_amount;
            }
        }

        /* 添加订单营销活动信息 */
        $data['order_list']['market_rate'] = 0;
        if($data['order_list']['order_activity_id'] > 0){
            $data['order_list']['actual_rent_total'] = $data['order_list']['order_activity_rent'];
            $rent_min_num = Db::table("rent_period")->where("rent_period_goods_id = {$data['order_list']['order_goods_id']} and rent_period_type = {$data['order_list']['rent_period_type']}")->value("rent_period_min_rent") ;
            if(empty($rent_min_num)){
                $data['order_list']['market_rate'] = round($data['order_list']['order_activity_rent']/($data['order_list']['order_rent_money']*$data['order_list']['order_time_number']*$data['order_list']['goods_amount'])*100);
            }else{
                $data['order_list']['market_rate'] = round(($data['order_list']['order_activity_rent']/$data['order_list']['goods_amount']-$data['order_list']['order_rent_money']*($data['order_list']['order_time_number']-$rent_min_num))/$rent_min_num/$data['order_list']['rent_period_now_rent_price']*100);
            }
        }else{
            $data['order_list']['actual_rent_total'] = $data['order_list']['order_total_price']-$data['order_list']['order_deposit']-$data['order_list']['order_freight'];
        }
        //订单实际租金
        $data['order_list']['order_total_price'] = $data['order_list']['actual_rent_total'];
        //订单付款租金
        $data['order_list']['actual_rent_total'] = $data['order_list']['actual_rent_total'] + $data['order_list']['relet_rent_price']-$data['order_list']['coupon_amount']-$data['order_list']['store_coupon_amount'];
        //订单总付款
        $data['order_list']['pay_price'] = $data['order_list']['pay_price'] + $data['order_list']['relet_price'];
        $data['type'] = input('get.type', 0);
        return view('jiesuan', ['data' => $data]);
    }

    /*
     * 添加订单结算单数据
    */
    public function jiesuan_add(){
        $merchant_id=session('merchant.merchant_id');
        if(input('post.settlement_bill_merchant_id') != $merchant_id){
            return returnJson('300', '你无权操作改该订单', '');
        }
        //判断结算小计金额不能小于0!
        $settlement_bill_total=input('post.settlement_bill_total');
        if($settlement_bill_total<0)
        {
           return returnJson('-1', '结算小计金额不能小于0!', '');
        }
        //结算小计金额不能大于实付款！
        $pay_price=input('post.pay_price');
        if($settlement_bill_total>$pay_price)
        {
            return returnJson('2', '结算小计金额不能大于实付款！', '');
        }

        $data['settlement_bill_liquidated'] = input('post.settlement_bill_liquidated');
        $data['settlement_bill_damages'] = input('post.settlement_bill_damages');
		$data['settlement_bill_total'] = input('post.settlement_bill_total');
        $data['settlement_bill_order_id'] = input('post.settlement_bill_order_id');
        $data['settlement_bill_goods_id'] = input('post.settlement_bill_goods_id');
        $data['settlement_bill_merchant_id'] = $merchant_id;
        $data['settlement_bill_remarks'] = input('post.settlement_bill_remarks');

        $order_id = input('post.settlement_bill_order_id');
        $orderdata = Db::table('goods_order')->alias('a')->
		 join('goods g','g.goods_id=a.order_goods_id','left')
		 ->where('order_id', 'eq', $order_id)->find();
		 
		  
		if($orderdata['order_refund_goods_status']==2)
		{
			//卖家退款退货已出具结算单
			$msg='您好，您申请退货的商品'.$orderdata['goods_name'].'商家已出具结算单，订单编号为'.$orderdata['order_order_sn'].'，请您查看后及时确认结算单。';
		    $modelcode='SMS_90305086';//'SMS_89960001';
        } 
		else
		{
			//卖家已结算
			$msg='您好，您的商品'.$orderdata['goods_name'].'商家已出具结算单，订单编号为'.$orderdata['order_order_sn'].',请您查看后及时确认结算单。';
		    $modelcode='SMS_90220049';//'SMS_89055038';
        }
        $date = [
            'order_shipping_status'=> '5',
        ];
        $msg_order=[
            'merchant_id' => $merchant_id,
            'create_time'=> time(),
            'type'=> 2,
			'order_id'=>$order_id,
			'user_id'=>$orderdata['order_user_id'],
			'title'=>'订单消息',
			'content'=>$msg,
        ];
        SettlementBillModel::settlement_bill_add($data);
        OrderModel::order_shipping_edit($order_id, $date);
        Db::table('goods_order_time')->where('order_id', 'eq', $order_id)->update(['order_settlement_bill_generation_time' => time(),]);
        Db::table('message_order')->insert($msg_order);
        $user_tel=Db::table('user')
		->alias('a')
		->where('user_id','eq',$orderdata['order_user_id'])->find();
        $order_sn= '***'.substr($orderdata['order_order_sn'], -6);
        $usertel=$user_tel['user_phone'];
        $ParamString = "{'ordersn':'$order_sn'}";
       // $this->OrderSendMessage($ParamString,$usertel,'租介',$modelcode);
        $tool=new Tools();
        $tool->sendMessage($ParamString, $usertel, '租介', $modelcode);
        return returnJson('1', '结算成功!');
	 }
    /*
     * 订单详情页
    */
    public function details(){
        $orderId = input('get.id');
        $data['order'] = Db::table('goods_order')->alias('order')
                        ->join('goods_order_message gom','order.order_id = gom.order_id', 'left')
                        ->join('goods_order_receipt gor','order.order_id = gor.order_id', 'left')
                        ->join('goods_order_pay gop','order.order_id = gop.order_id', 'left')
                        ->join('goods g', 'order.order_goods_id = g.goods_id', 'left')
                        ->join('goods_order_time got', 'order.order_id = got.order_id', 'left')
                        ->join('goods_order_rent grent', 'order.order_id = grent.order_id', 'left')
                        ->join('user u', 'order.order_user_id = u.user_id', 'left')
						->join('goods_order_refund w', 'order.order_id = w.order_id', 'left')
                        ->join('goods_order_deliver gorf', 'order.order_id = gorf.order_id','left')
                        ->join('since se','gorf.order_since_id=se.since_id','left')
                        ->where('order.order_id', 'eq', $orderId)
                        ->find();
        $data['order']['relet_price'] = 0;
        $data['order']['coupon_amount'] =0;
        $data['order']['store_coupon_amount'] =0;
        $data['order']['relet_price'] = 0;
        $data['order']['relet_rent_price'] = 0;
        /*处理红包减免*/
        $coupon_info = Db::table("zj_coupon_use")->alias("zcu")
            ->join('zj_coupon zc','zc.id=zcu.coupon_id','left')
            ->field("zc.use_range,zcu.used_amount")
            ->where("zcu.coupon_no in ('{$data['order']['coupon_no']}','{$data['order']['store_coupon_no']}')")
            ->select();
        if(!empty($coupon_info)){
            if(count($coupon_info) == 1){
                $data['order']['coupon_amount'] = $coupon_info[0]['use_range'] == 1 ? $coupon_info[0]['used_amount'] : 0;
                $data['order']['store_coupon_amount'] = $coupon_info[0]['use_range'] == 2 ? $coupon_info[0]['used_amount'] : 0;
            }else{
                foreach($coupon_info as $k => $v){
                    if($v['use_range'] == 1){
                        $data['order']['coupon_amount'] =$v['used_amount'];
                    }else{
                        $data['order']['store_coupon_amount'] =$v['used_amount'];
                    }
                }
            }
        }
        $relet_where = [
            'order.relet_origin_id' => $orderId,
            'order.relet_status' => 2,
            'order.order_is_delete' => 0,
            'gop.order_status' => 2,
        ];
        $relet_order = Db::table('goods_order')->alias('order')
            ->field('order.order_id,order.order_order_sn,order.coupon_no,order.store_coupon_no,order.actual_price,order.order_total_price')
            ->join('goods_order_pay gop','order.order_id = gop.order_id')
            ->where($relet_where)
            ->select();
        $relet_coupon_amount = $relet_store_coupon_amount = 0;
        if(!empty($relet_order)) {
            foreach ($relet_order as $k => $v) {
                //续租实际付款金额
                $data['order']['relet_price'] = $data['order']['relet_price'] + $v['actual_price'];
                /*处理红包减免*/
                $relet_coupon_info = Db::table("zj_coupon_use")->alias("zcu")
                    ->join('zj_coupon zc', 'zc.id=zcu.coupon_id', 'left')
                    ->field("zc.use_range,zcu.used_amount")
                    ->where("zcu.coupon_no in ('{$v['coupon_no']}','{$v['store_coupon_no']}')")
                    ->select();
                if (!empty($relet_coupon_info)) {
                    if (count($relet_coupon_info) == 1) {
                        $relet_coupon_amount = $relet_coupon_info[0]['use_range'] == 1 ? $relet_coupon_info[0]['used_amount'] : 0;
                        $relet_store_coupon_amount = $relet_coupon_info[0]['use_range'] == 2 ? $relet_coupon_info[0]['used_amount'] : 0;
                    } else {
                        foreach ($relet_coupon_info as $k => $v) {
                            if ($v['use_range'] == 1) {
                                $relet_coupon_amount = $v['used_amount'];
                            } else {
                                $relet_store_coupon_amount = $v['used_amount'];
                            }
                        }
                    }
                }
                //续租实际租金
                $data['order']['relet_rent_price'] = $data['order']['relet_rent_price'] + $v['order_total_price'];
                $data['order']['coupon_amount'] += $relet_coupon_amount;
                $data['order']['store_coupon_amount'] += $relet_store_coupon_amount;
            }
        }
        /* 添加订单营销活动信息 */
        $data['order']['market_rate'] = 0;
        if($data['order']['order_activity_id'] > 0){
            //原订单活动租金
            $data['order']['order_rent_price'] = $data['order']['order_activity_rent'];
            $rent_min_num = Db::table("rent_period")->where("rent_period_goods_id = {$data['order']['order_goods_id']} and rent_period_type = {$data['order']['rent_period_type']}")->value("rent_period_min_rent") ;
            if(empty($rent_min_num)){
                $data['order']['market_rate'] = round($data['order']['order_activity_rent']/($data['order']['order_rent_money']*$data['order']['order_time_number']*$data['order']['goods_amount'])*100);
            }else{
                $data['order']['act_rent'] = round(($data['order']['order_activity_rent']/$data['order']['goods_amount']-$data['order']['order_rent_money']*($data['order']['order_time_number']-$rent_min_num))/$rent_min_num/$data['order']['rent_period_now_rent_price']*100);
            }
        }else{
            //原订单租金
            $data['order']['order_rent_price'] = $data['order']['order_total_price']-$data['order']['order_deposit']-$data['order']['order_freight'];
        }
        //实际租金
        $data['order']['order_rent_price'] = $data['order']['order_rent_price']+$data['order']['relet_rent_price'];
        //实际支付金额
        $data['order']['actual_rent_total'] = $data['order']['actual_price']+ $data['order']['relet_price'];
        //获取结算单信息
		$res = Db::table('settlement_bill')->where('settlement_bill_order_id', 'eq', $data['order']['order_id'])->find();
		$ship_count_down = (time()-$data['order']['order_shipping_time']) < 86400 ? (86400-(time()-$data['order']['order_shipping_time'])) : 0 ;
        $data['order']['ship_count_down'] = $ship_count_down;
	    $ress =Db::table('goods_order_receipt')->alias('gor')
                        ->join('goods_order_deliver god','gor.order_id = god.order_id')
                        ->where('gor.order_id', 'eq', $orderId)
                        ->find();
		//获取归还物流信息

        if($data['order']['order_express_type']!=2)
        {
            if(intval( $data['order']['order_refund_goods_status'])==2||intval( $data['order']['order_refund_goods_status'])==4)
            {
                $revert_info = Db::table('goods_order_refund')->alias('a')
                    ->join('revert b', 'a.order_refund_revertid=b.revert_id', 'left')
                    ->join('since se', 'a.order_since_id=se.since_id', 'left')
                    ->where('a.order_id', 'eq', $orderId)
                    ->find();
                if ($data['order']['order_express_type'] == 1)
                {

                $data['return_expressid'] = $revert_info['order_deliver_expressid'];
                $data['return_deliver_company'] = $revert_info['order_deliver_company'];
                $data['revent_tel'] = $revert_info['revent_tel'];
                $data['revent_name'] = $revert_info['revent_receiver_name'];
                $data['revent_province'] = $revert_info['revent_province'];
                $data['revent_city_name'] = $revert_info['revent_city'];
                $data['revent_region_name'] = $revert_info['revent_region'];
                $data['revent_detailed_address'] = $revert_info['revent_detailed_address'];
                $data['is_revert'] = 1;
                }
                if ($data['order']['order_express_type'] == 3)
                {
                    $data['since_tel'] = $revert_info['since_tel'];
                    $data['since_name'] = $revert_info['since_name'];
                    $data['since_province'] = $revert_info['province_name'];
                    $data['since_city_name'] = $revert_info['city_name'];
                    $data['since_region_name'] = $revert_info['region_name'];
                    $data['since_detailed_address'] = $revert_info['since_detailed_address'];
                    $data['is_since'] = 1;
                }
            }
            if(intval( $data['order']['order_refund_goods_status'])==0) {
                $revert_info = Db::table('goods_order_return')->alias('a')
                    ->join('revert b', 'a.return_revertid=b.revert_id', 'left')
                    ->join('since se', 'a.since_id=se.since_id', 'left')
                    ->where('a.order_id', 'eq', $orderId)
                    ->find();
                if ($data['order']['order_express_type'] == 1) {

                    $data['return_expressid'] = $revert_info['return_expressid'];
                    $data['return_deliver_company'] = $revert_info['return_deliver_company'];
                    $data['revent_tel'] = $revert_info['revent_tel'];
                    $data['revent_name'] = $revert_info['revent_receiver_name'];
                    $data['revent_province'] = $revert_info['revent_province'];
                    $data['revent_city_name'] = $revert_info['revent_city'];
                    $data['revent_region_name'] = $revert_info['revent_region'];
                    $data['revent_detailed_address'] = $revert_info['revent_detailed_address'];
                    $data['is_revert'] = 1;
                }
                if ($data['order']['order_express_type'] == 3) {
                    $data['since_tel'] = $revert_info['since_tel'];
                    $data['since_name'] = $revert_info['since_name'];
                    $data['since_province'] = $revert_info['province_name'];
                    $data['since_city_name'] = $revert_info['city_name'];
                    $data['since_region_name'] = $revert_info['region_name'];
                    $data['since_detailed_address'] = $revert_info['since_detailed_address'];
                    $data['is_since'] = 1;
                }
            }
        }
        //获取结算单信息
        $data['settlement_bill_liquidated'] = $res['settlement_bill_liquidated'];
        $data['settlement_bill_damages'] = $res['settlement_bill_damages'];
        $data['settlement_bill_remarks'] = $res['settlement_bill_remarks'];
        $data['settlement_bill_total'] = $res['settlement_bill_total'];
        return view('details', ['data' => $data]);
    }
    /*
     * 获取财务信息
    */
    public function bill(){
        $year = input('get.year');
        $may = input('get.may');
        $merchant_id = session('merchant.merchant_id');
        $starttime = date('Y-m-01 00:00:00', strtotime($year."-".$may.'-1'));
        $endtime = date('Y-m-d 23:59:59', strtotime("$starttime +1 month -1 day"));
        $start = strtotime($starttime);
        $end = strtotime($endtime);
        $data['year'] = date('Y', strtotime($starttime));
        $data['may'] = date('m', strtotime($starttime));
        $data['order_list'] = Db::table('goods_order')->alias('go')
                        ->field('go.*')
                        ->field('got.order_pay_time, got.order_delivery_time, got.order_settlement_bill_confirm_time, got.order_shipping_time, got.order_goods_rent_time, got.order_goods_return_time')
                        ->field('g.goods_name')
                        ->field('b.*')
                        ->join('goods g', 'go.order_goods_id = g.goods_id')
                        ->join('goods_order_time got', 'go.order_id = got.order_id')
                        ->join('settlement_bill b','b.settlement_bill_order_id = go.order_id','left')
                        ->where('go.order_merchant_id', $merchant_id)
                        ->where(function ($query) use($start,$end){
                            //1、当月租,当月确认 + 上月租,当月确认
                            $query->where([
                                'got.order_goods_rent_time' => ['lt', "$end"],
                                'got.order_delivery_time' => ['between',[$start,$end]]
                            ]);
                        })
                        ->whereOr(function ($query) use($start,$end){
                            //2、当月租,上月确认
                            $query->where([
                                'got.order_goods_rent_time' => ['between',[$start,$end]],
                                'got.order_delivery_time' => [['>',0], ['<',"$start"],'and']
                            ]);
                        })
                        ->whereOr(function ($query) use($start,$end){
                            //2、上月租,上月确认,当月已经结算
                            $query->where([
                                'got.order_goods_rent_time' => [['>',0], ['<',"$start"],'and'],
                                'got.order_delivery_time' => [['>',0], ['<',"$start"],'and'],
                                'got.order_settlement_bill_confirm_time' => ['between',[$start,$end]]
                            ]);
                        })
                        ->group('go.order_id')
                        ->paginate(10,false,['query' => request()->param()]);
        $data['page'] = $data['order_list']->render();
        //var_dump($data['order_list']);die;
        foreach ($data['order_list'] as $key => &$list) {
            $list['commission'] = 0;
            if ($list['order_settlement_bill_confirm_time'] == 0) {
                //未出结算单,此种情况,有无退款计算方式都一样
                $data['aret'][$key]['commission'] = $list['order_rent_money'] * $list['order_rate'] / 100;  //佣金
                $data['aret'][$key]['total'] = $list['order_rent_money'] + $list['order_freight'] - $list['commission'];
            } else {
                //已出结算单
                if ($list['order_refund_goods_status'] == 0) {
                    //无退货
                    if ($list['order_goods_rent_time'] < $start && $list['order_delivery_time'] < $start && $list['order_settlement_bill_confirm_time'] >= $start && $list['order_settlement_bill_confirm_time'] <= $end) {
                        //上月租,上月确认,当月已经结算
                        $data['aret'][$key]['commission'] = ($list['settlement_bill_liquidated'] + $list['settlement_bill_damages']) * $list['order_rate'] / 100;
                        $data['aret'][$key]['total'] = $list['settlement_bill_liquidated'] + $list['settlement_bill_damages'] - $list['commission'];
                    } else {
                        //当月租,当月确认,当月已经结算
                        $data['aret'][$key]['commission'] = ($list['order_rent_money'] + $list['settlement_bill_liquidated'] + $list['settlement_bill_damages']) * $list['order_rate'] / 100;
                        $data['aret'][$key]['total'] = $list['order_rent_money'] + $list['settlement_bill_liquidated'] + $list['settlement_bill_damages'] + $list['order_freight'] - $list['commission'];
                    }
                } else {
                    //有退货
                    if ($list['order_goods_rent_time'] < $start && $list['order_delivery_time'] < $start) {
                        //上月租,上月确认,当月退货
                        $data['aret'][$key]['commission'] = ($list['settlement_bill_liquidated'] + $list['settlement_bill_damages'] - $list['order_rent_money']) * $list['order_rate'] / 100;
                        $data['aret'][$key]['total'] =  $list['settlement_bill_liquidated'] + $list['settlement_bill_damages'] - $list['order_rent_money'] - $list['commission'];
                    } else {
                        //当月租,当月确认,当月退货
                        $data['aret'][$key]['commission'] = ($list['settlement_bill_liquidated'] + $list['settlement_bill_damages']) * $list['order_rate'] / 100;
                        $data['aret'][$key]['total'] =  $list['settlement_bill_liquidated'] + $list['settlement_bill_damages'] - $list['commission'];
                    }
                }

            }
        }
        $data['end'] = $end;
        $data['start'] = $start;
        return view('bill', ['data' => $data]);
    }
    //绑定结算账单详情数据
    public function billdetail()
	{
		$year = input('get.year');
        $may = input('get.may');

        $merchant_id = session('merchant.merchant_id');
        $data= Db::table('zj_merchant_bill')->where('merchant_id', $merchant_id)->where(function ($query) use($year,$may){
                             $query->where([
                                'delete_time'=>['eq',0],
                                'year' => ['eq',$year],
                                 'month' => ['eq',$may]
                            ]);
                        })->paginate(30,false,['query' => request()->param()]);

		    $result=Db::table('zj_merchant_bill')
            ->field('sum(IFNULL(rent_money,0))rent_money,sum(IFNULL(freight_money,0))freight_money')
            ->field('sum(IFNULL(liquidated_money,0))liquidated_money,sum(IFNULL(damages_money,0))damages_money')
            ->field('sum(IFNULL(total_money,0))total_money')
            ->where('merchant_id', $merchant_id)
            ->where(function ($query) use($year,$may){
                             $query->where([
                                 'delete_time'=>['eq',0],
                                 'year' => ['eq',$year],
                                 'month' => ['eq',$may]
                            ]);
                        })->find();
        return view('bill', ['data' => $data,'year' => $year,'may' => $may,'result'=>$result]);
	}
	//导出结算账单详情数据
	public function billToExcel()
	{
		$year = input('get.year');
        $may = input('get.may');
		 
        //获取结算单数据
        $billdata = OrderModel::excelBill($year,$may);
        //结算帐单的Excel导出操作
        $excel_name=$year.'-'.$may.'结算帐单';
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G','H','I');
        //表头数组
        $tableheader = array(
            '订单号',
            //'确认收货时间',
            '商品名称',
            //'租赁时间','归还时间','结算时间',
            '订单状态',
            '租金',
            '运费',
            '违约金',
            '损失赔偿金',
            //'费率',
            '拥金',
            '合计金额');
        //输出Excel
        $excel= new Tools();
        $excel->toExcel($letter,$tableheader,$billdata,$excel_name);
	}
	//发送短信公共方法
    function OrderSendMessage($ParamString, $RecNum, $SignName, $TemplateCode)
    {
        $host = "http://sms.market.alicloudapi.com";
        $path = "/singleSendSms";
        $method = "GET";
        $appcode = "1bf3b3c9756b40a6b3a6d19d9e6ef417";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "ParamString=$ParamString&RecNum=$RecNum&SignName=$SignName&TemplateCode=$TemplateCode";
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_exec($curl);
        curl_close($curl);
    }



}
